import axios from "axios";
import {type BbsCodeBody, buildEmoteGroup, buildIndexForumBody, buildUiResource} from "../types/Resources.ts";
import {decodeFromGB18030} from "../utils/encoding.ts";

export class ResourceApi {
    readonly baseUrl: string;

    constructor(baseUrl: string) {
        this.baseUrl = baseUrl;
    }

    bbsCode = () => axios.get("common_res/js_bbscode_core.js", {baseURL: this.baseUrl}).then(res => {
        const text = res.data;

        // 颜色
        const colorMatcher = /ubbcode\.fontColor = (\{[\s\S]+?})/.exec(text);
        const colorJson = colorMatcher?.[1] ? JSON.parse(colorMatcher?.[1]?.replace(/'/g, "\"")) : undefined

        const emoteMatcher = /ubbcode\.smiles = (\{[\s\S]+?}\/\/s)/.exec(text);
        const emoteText = emoteMatcher?.[1]
            ?.replace(/'/g, "\"")
            ?.replace(/(\w+):/g, "\"$1\":")
            ?.replace(/\/\/.+/g, "")
        // console.log('emoteText', emoteText)
        const emoteJson = emoteText ? JSON.parse(emoteText) : undefined
        // console.log('emoteJson', emoteJson)
        return {
            fontColor: colorJson ? Object.keys(colorJson) : [],
            emoteGroups: buildEmoteGroup(emoteJson)
        } as BbsCodeBody
    })

    indexForums = () => axios.get("proxy/cache_attach/bbs_index_data.js", {
        baseURL: this.baseUrl,
        responseType: 'arraybuffer',
        transformResponse: [(data) => decodeFromGB18030(data)]
    }).then(res => {
        const json = JSON.parse(res.data.replace('window.script_muti_get_var_store=', ''))
        return buildIndexForumBody(json)
    })

    uiResource = () => axios.get("common_res/js_commonui.js", {baseURL: this.baseUrl,}).then(res => buildUiResource(res.data))
}


